import React, { Component } from 'react';
import {
  View,
  ImageBackground,
  Image,
  Keyboard,
  TouchableWithoutFeedback,
  DeviceEventEmitter,
  Platform,
  TouchableOpacity,
  Linking,
} from 'react-native';
import {
  Text,
  Button,
  Form,
  Item,
  Input,
  Picker,
} from 'native-base';
import SplashScreen from 'react-native-splash-screen';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import DeviceInfo from 'react-native-device-info';
import { UtilToast } from '../../utils/util-method';
import { CheckBox } from '../../components';
import theme from '../../native-base-theme/variables';
import { Storage, notice, Constants } from '../../utils';
import {
  setAlias, setTags, getRegistrationID, addJPushListener,
} from '../../utils/jpush';
import { checkIsNeedUpdate } from '../../utils/version';
import * as authService from '../../services/auth';
import * as messageService from '../../services/message';
import * as userService from '../../services/user';
import I18n from '../../res/language';
import { loginscreenBg } from './constant';
import styles from './styles';
import { queryEquipmentByparams } from '../../services/todo';
import * as devicesRequest from '../../services/devicesRequest';
import { findLatestVersion } from '../../services/version';
import { FormSearchChoice } from '../../components';

const INVALID_COLOR = 'red';
const INVALID_HINT = '必须是6～16位字符或数字';
const INVALID_REG = /[\d\w_]{6,16}/;

class LoginPage extends Component {
  static navigationOptions = {
    header: null,
  }

  count = 0;

  constructor(props) {
    super(props);
    this.state = {
      groupCode: '',
      username: '',
      password: '',
      showSecurity: false,
      securityBASE64: '',
      securityCode: '',
      group: { id: '', name: '' },
      modalVisible: false,
      rememberPass: true,
    };
  }

  componentDidMount() {
    this._serUsername();
    this._initIpconfig();
    DeviceEventEmitter.addListener('toUpdataAppEvent', () => {
      this.props.navigation.navigate({ routeName: 'Version' });
    });

    if (Platform.OS === 'android') {
      this.queryLatestVersion();
    } else {
      // ios 跳转至appstore
    }
    // this._serUsername();
    // this._initIpconfig();
    // this.userInfo();
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('toUpdataAppEvent');
  }

  onLogin = async () => {
    // const payload = {
    //   username: this.state.username,
    //   password: this.state.password,
    //   securityCode: this.state.securityCode,
    //   loginCode: this.state.groupCode,
    // };
    const payload = {
      username: this.state.username,
      password: this.state.password,
      securityCode: this.state.securityCode,
    };
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const token = await authService.login(payload);
      // console.time('login time:');
      if (token && token.access) {
        await Storage.set('token.access', token.access);
        await Storage.set('username', this.state.username);
        await Storage.set('groupCode', this.state.groupCode);
        // await Storage.set('groupName', this.state.group.name);

        if (this.state.rememberPass) {
          await Storage.set('password', this.state.password);
          await Storage.set('rememberPass', true);
        } else {
          await Storage.set('password', '');
          await Storage.set('rememberPass', false);
        }
        global.__TOKEN_ACCESS__ = token.access;
        global.groupCode = this.state.groupCode;
        global.user = await userService.infoOfUserAndStaffCarryResources();
        this.queryRole();
        this.querySafeDepInfo();
        this.props.navigation.navigate({ routeName: 'Main' });
        this.setState({ password: '', showSecurity: false, securityCode: '' });
        this.registerToPush();
      } else {
        const { action, securityCode } = token.error.response;
        if (action && action.split(',').includes('show_patcha')) {
          const base64 = 'data:image/png;base64,';
          // 添加二维码
          // yield put(createAction('updateState')({ securityBASE64: base64 + securityCode, showSecurity: true }));
          this.setState({ securityBASE64: base64 + securityCode, showSecurity: true });
        }
      }
      DeviceEventEmitter.emit('showLoading', false);
    } catch (e) {
      console.error(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  get usernameLabelColor() {
    return this._rInvalidUsername() ? INVALID_COLOR : '#fff';
  }

  get usernameLabelText() {
    return this._rInvalidUsername() ? INVALID_HINT : '用户名';
  }

  get passwordLabelColor() {
    return this._rInvalidPassword() ? INVALID_COLOR : '#fff';
  }

  get passwordLabelText() {
    return this._rInvalidPassword() ? INVALID_HINT : '密码';
  }

  get invalidLogin() {
    return this.invalidUsername || this.invalidPassword;
  }

  get invalidUsername() {
    return !(INVALID_REG.test(this.state.username));
  }

  get invalidPassword() {
    return !(INVALID_REG.test(this.state.password));
  }

  queryLatestVersion = async () => {
    try {
      const currentVersion = DeviceInfo.getVersion();
      const response = await findLatestVersion({
        version: currentVersion, appId: Constants.APP_ID,
      });
      const {
        version: latestVersion, updatePolicy, updatePolicyValue, downloadAddr, fileGroup,
      } = response.data;
      const downloadPath = `/${fileGroup}/${downloadAddr}`;
      global.downloadPath = downloadPath;
      if (latestVersion === null || currentVersion == latestVersion) { // 没有版本更新
        this.userInfo();
      } else { // 有版本更新
        SplashScreen.hide();// 让splash页面消失
        checkIsNeedUpdate({
          currentVersion, latestVersion, updatePolicy, updatePolicyValue,
        });
      }
    } catch (e) {
      SplashScreen.hide();// 让splash页面消失
      console.error(e);
    }
  }

  userInfo = async () => {
    try {
      global.__TOKEN_ACCESS__ = await Storage.get('token.access', null);
      global.groupCode = await Storage.get('groupCode', null);
      if (global.__TOKEN_ACCESS__ && global.groupCode) {
        global.user = await userService.infoOfUserAndStaffCarryResources();
        this.queryRole();
        this.querySafeDepInfo();
        this.setState({ password: '', showSecurity: false, securityCode: '' });
        this.props.navigation.navigate({ routeName: 'Main' });
        this.registerToPush();
      }
      SplashScreen.hide();// 让splash页面消失
    } catch (e) {
      console.error(e);
      SplashScreen.hide();// 让splash页面消失
    }
  }

  // 根据用户ID 查询角色信息
  queryRole = async () => {
    const ajaxData = global.user.id;
    try {
      const list = await devicesRequest.getQueryRoles(ajaxData);
      global.roles = list.data;
    } catch (error) {
      console.error(error);
    }
  }

  querySafeDepInfo = async () => {
    try {
      const list = await devicesRequest.getQuerySageDepInfo();
      global.safeDep = list.data;
    } catch (error) {
      console.error(error);
    }
  }

  // 初始化配置的IP
  _initIpconfig = async () => {
    global.IP_CONFIG = await Storage.get('ipConfig', '');
  }

  _serUsername = async () => {
    const groupCode = await Storage.get('groupCode', '');
    const username = await Storage.get('username', '');
    const password = await Storage.get('password', '');
    const rememberPass = await Storage.get('rememberPass', true);
    this.setState({
      username,
      groupCode,
      password,
      rememberPass,
    });
  }

  _rInvalidUsername = () => (this.state.username.length !== 0) && this.invalidUsername;

  _rInvalidPassword = () => (this.state.password.length !== 0) && this.invalidPassword;

  _onLogin = () => {
    Keyboard.dismiss();
    // if (this.state.groupCode == '') {
    //   UtilToast('请输入企业码', 'danger');
    //   return;
    // }
    if (this.state.username.length !== 0 && this.state.password.length !== 0) {
      if (this.state.showSecurity && this.state.securityCode.length < 1) {
        UtilToast('请输入验证码', 'danger');
      } else {
        this.onLogin();
      }
    } else {
      UtilToast('用户名或密码不能为空', 'danger');
    }
  }

  onSecurityCodeClick = async () => {
    const res = await authService.refreshSecurity(this.state.username);
    if (res.success) {
      const base64 = 'data:image/png;base64,';
      this.setState({ securityBASE64: base64 + res.data.data, showSecurity: true });
    }
  }

  open = () => {
    const url = 'https://itunes.apple.com/cn/app/%E6%B6%A6%E9%91%AB%E8%AE%BE%E5%A4%87/id1448989175?mt=8';
    Linking.openURL(url);
  }

  onChoiceGroup = () => {
    this._choiceConfirm = (it) => {
      this.setState({ group: { id: it[0].id, name: it[0].name } });
    };
    this.searchUri = '/api-ms/system/tenant/getTenantAll';
    this._showModal();
  }

  _showModal = () => {
    this.setState({
      modalVisible: true,
    });
  }

  searchUri = "";

  searHeaderTitle = '请选择使用公司';

  _choiceConfirm = null;

  _cancelModal = () => {
    this.setState({ modalVisible: false });
  }

  _renderLoginForm = () => (
    <View style={styles.formContainer}>
      {this.state.modalVisible && (
        <FormSearchChoice
          onClose={this._cancelModal}
          searchUri={this.searchUri}
          type="radio"
          title={this.searHeaderTitle}
          searchNoHeader
          choiceConfirm={this._choiceConfirm}
        />
      )}
      <Form>
        {/* <Item fixedLabel style={{ marginLeft: 0 }} onPress={this.onChoiceGroup}>
          <View style={{ backgroundColor: 'white', padding: 5, borderRadius: 60 }}>
            <Icon
              name="city"
              size={20}
              color={theme.myPrimary}
              style={{ width: 20, height: 20 }}
            />
          </View>
          <Input
            placeholder="请选择使用公司"
            value={this.state.group.name}
            placeholderTextColor="white"
            editable={false}
            style={styles.loginText}
          />
          <Icon active name="menu-down" size={25} color="white" />
        </Item> */}
        <Item fixedLabel style={{ marginLeft: 0 }}>
          <View style={{ backgroundColor: 'white', padding: 5, borderRadius: 60 }}>
            <Icon
              name="account"
              size={20}
              color={theme.myPrimary}
              style={{ width: 20, height: 20 }}
            />
          </View>
          {/* <Label style={{ color: this.usernameLabelColor, fontSize: 16 }}>
            { this.usernameLabelText }
          </Label> */}
          <Input
            placeholder="用户名"
            value={this.state.username}
            onChangeText={(username) => { this.setState({ username }); }}
            placeholderTextColor="white"
            style={styles.loginText}
          />
        </Item>
        <Item fixedLabel style={{ marginLeft: 0 }}>
          <View style={{ backgroundColor: 'white', padding: 5, borderRadius: 60 }}>
            <Icon
              name="lock"
              size={20}
              color={theme.myPrimary}
              style={{ width: 20, height: 20 }}
            />
          </View>
          {/* <Label style={{ color: this.passwordLabelColor, fontSize: 16 }}>
            { this.passwordLabelText }
          </Label> */}
          <Input
            secureTextEntry
            placeholder="密码"
            value={this.state.password}
            onChangeText={(password) => { this.setState({ password }); }}
            placeholderTextColor="white"
            style={styles.loginText}
          />
        </Item>
        {/* <Item fixedLabel style={{ marginLeft: 0 }}>
          <View style={{ backgroundColor: 'white', padding: 5, borderRadius: 60 }}>
            <Icon
              name="city"
              size={20}
              color={theme.myPrimary}
              style={{ width: 20, height: 20 }}
            />
          </View>
          <Input
            placeholder="请输入企业码"
            value={this.state.groupCode}
            onChangeText={(groupCode) => { this.setState({ groupCode }); }}
            placeholderTextColor="white"
            style={styles.loginText}
          />
        </Item> */}
        { this.state.showSecurity && (
          <Item fixedLabel style={{ marginLeft: 0 }}>
            <Input
              placeholder="验证码"
              style={{
                color: 'white', fontSize: 17,
              }}
              value={this.state.securityCode}
              onChangeText={(value) => {
                this.setState({ securityCode: value });
              }}
              keyboardAppearance="light"
              autoCapitalize="none"
              autoCorrect={false}
              keyboardType="numeric"
              returnKeyType="done"
              clearButtonMode="always"
            />
            <View
              style={{
                width: '50%',
                height: '100%',
              }}
            >
              <TouchableOpacity
                style={{ flex: 1 }}
                activeOpacity={1}
                onPress={this.onSecurityCodeClick}
              >
                <Image
                  style={{ flex: 1, backgroundColor: 'white' }}
                  source={{
                    uri: this.state.securityBASE64,
                  }}
                />
              </TouchableOpacity>
            </View>
          </Item>
        )}
      </Form>
      <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 8 }}>
        <CheckBox
          style={styles.checkBox}
          checked={this.state.rememberPass}
          onCheckChange={(rememberPass) => this.setState({ rememberPass })}
        />
        <Text style={[styles.loginText, { marginLeft: 8 }]}>记住密码</Text>
      </View>
      <Button
        full
        style={styles.loginBtn}
        onPress={this._onLogin}
      >
        <Text style={styles.loginText}>登  录</Text>
      </Button>
    </View>
  )

  registerToPush = async () => {
    const tag = 'DEV';
    const appId = Constants.APP_ID;
    const userCode = global.user.name;
    const alias = `${tag}_${userCode}`;
    let registerId = '';
    getRegistrationID().then(tRegisterId => {
      registerId = tRegisterId;
      if (!registerId) {
        console.error('getRegisterId fail');
        registerId = '1104a8979286e33aabd';
      }
      setAlias(alias).then(isSetAlias => {
        if (!isSetAlias) {
          console.error('setAlias fail');
        }
        setTags(tag).then(isSetTag => {
          if (!isSetTag) {
            console.error('setTag fail');
          }
          addJPushListener();
          try {
            messageService.registerToPush({
              alias,
              appId,
              pushPlatform: 0,
              registerId,
              userCode,
              tag,
            });
          } catch (e) {
            console.error(e);
          }
        });
      });
    });

    // if (!registerId) {
    //   console.error('getRegisterId fail');
    // }

    // const isSetAlias = await setAlias(alias);
    // if (!isSetAlias) {
    //   console.error('setAlias fail');
    // }

    // const isSetTag = await setTags(tag);
    // if (!isSetTag) {
    //   console.error('setTag fail');
    // }
    // addJPushListener();

    // 和后台服务绑定推送别名TAG等信息
    // try {
    //   messageService.registerToPush({
    //     alias,
    //     appId,
    //     pushPlatform: 0,
    //     registerId,
    //     userCode,
    //     tag,
    //   });
    // } catch (e) {
    //   console.error(e);
    // }
  }

  _toConfig = () => {
    if (this.count === 0) {
      setTimeout(() => {
        this.count = 0;
      }, 2000);
    }
    this.count = this.count + 1;
    if (this.count === 5) {
      this.props.navigation.navigate({ routeName: 'Config' });
    }
  }

  render() {
    const footer = (
      <ImageBackground resizeMode="stretch" source={loginscreenBg} style={styles.footerContainer}>
        <Text style={styles.footerText}>版权所有 中铝视拓智能科技有限公司</Text>
      </ImageBackground>
    );
    const dismissKeyboard = () => {
      Keyboard.dismiss();
    };
    return (
      <TouchableWithoutFeedback onPress={dismissKeyboard} style={styles.pageContainer}>
        <View style={styles.container}>
          <View style={styles.mianContainer}>
            <View style={styles.logoContainer}>
              <TouchableWithoutFeedback onPress={this._toConfig}>
                <Image source={require('../../../assets/images/logo.png')} style={styles.logo} />
              </TouchableWithoutFeedback>
              <Text style={styles.logo_text}>智能工厂</Text>
            </View>

            { this._renderLoginForm() }
          </View>

          { footer }
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

export default LoginPage;
